package cn.schoolwow.quickdao.test.module.business.user.transaction.commit.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.entity.UserRole;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

public class CommitUserRoleTransactionFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);

        try (Transaction transaction = dao.startTransaction();){
            flowContext.putInstanceData(transaction, Transaction.class, FlowContextDataRange.CurrentFlow);
            insertUser(flowContext);
            insertRole(flowContext);
            insertUserRole(flowContext);
            commit(flowContext);
        }
    }

    @Override
    public String name() {
        return "用户角色事务提交";
    }

    private void insertUser(FlowContext flowContext){
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        User user = new User();
        user.setUsername("user0");
        user.setPassword("123456");
        user.setEmail("user0@fake.com");
        user.setMobile("12345678911");

        int effect = transaction.insert(user);
        Assert.assertEquals(1, effect);

        flowContext.putTemporaryData("insertUser", user);
    }

    private void insertRole(FlowContext flowContext){
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        Role role = new Role();
        role.setRoleKey("admin");
        role.setRoleName("管理员");
        role.setStatus(1);

        int effect = transaction.insert(role);
        Assert.assertEquals(1, effect);

        flowContext.putTemporaryData("insertRole", role);
    }

    private void insertUserRole(FlowContext flowContext){
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        UserRole userRole = new UserRole();
        userRole.setUserId(insertUser.getId());
        userRole.setRoleId(insertRole.getId());

        int effect = transaction.insert(userRole);
        Assert.assertEquals(1, effect);

        flowContext.putTemporaryData("insertUserRole", userRole);
    }

    private void commit(FlowContext flowContext){
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        transaction.commit();
    }
}
